<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" />
        </div>
      </template>

      <!-- 快速切换 登录/注册 -->
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">
          {{ formType === 0 ? '去注册' : '去登录' }}
        </el-link>
      </div>

      <!-- 表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
        style="max-width: 360px; margin: 0 auto"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="手机号"
            :prefix-icon="UserFilled"
          />
        </el-form-item>

        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 验证码仅注册时显示 -->
        <el-form-item v-if="formType === 1" prop="validCode">
          <el-input
            v-model="loginForm.validCode"
            placeholder="验证码"
            :prefix-icon="Lock"
          >
            <template #append>
              <span style="cursor: pointer; user-select: none" @click="handleSmsCode">
                {{ countdown.validText }}
              </span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="submitForm(loginFormRef)">
            {{ formType === 0 ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { ref, reactive,computed,toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { getCode,userAuthentication,login, menuPermissions } from '../../api'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { da, el, lo } from 'element-plus/es/locales.mjs'


/* ---------- 表单数据 ---------- */
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode: ''
})

/* ---------- 登录/注册切换 ---------- */
const formType = ref(0) // 0 登录  1 注册
const handleChange = () => (formType.value = formType.value === 0 ? 1 : 0)

/* ---------- 校验规则 ---------- */
const validateUser = (_, value, callback) => {
  if (!value) return callback(new Error('请输入手机号'))
  const phoneReg = /^1[3-9]\d{9}$/
  phoneReg.test(value) ? callback() : callback(new Error('手机号格式不正确'))
}

const validatePass = (_, value, callback) => {
  if (!value) return callback(new Error('请输入密码'))
  // 同时包含字母+数字，长度 6-16
  const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{6,16}$/
  reg.test(value) ? callback() : callback(new Error('6-16 位，需同时包含字母和数字'))
}

const rules = {
  userName: [{ validator: validateUser, trigger: 'blur' }],
  passWord: [{ validator: validatePass, trigger: 'blur' }],
  validCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

/* ---------- 验证码倒计时 ---------- */
const loginFormRef = ref()
const router = useRouter()
const store = useStore()

const countdown = reactive({
  validText: '获取验证码',
  time: 60
})
let timer = null

const handleSmsCode = () => {
  // 防止重复点击
  if (timer) return
  // 简单校验手机号
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(loginForm.userName)) {
    return ElMessage.warning('请先输入正确的手机号')
  }

  // 这里调你的接口发验证码
  // console.log('【假请求】给', loginForm.userName, '发短信')

  countdown.time = 60
  countdown.validText = `剩余 ${countdown.time}s`
  timer = setInterval(() => {
    countdown.time -= 1
    if (countdown.time <= 0) {
      clearInterval(timer)
      timer = null
      countdown.validText = '获取验证码'
    } else {
      countdown.validText = `剩余 ${countdown.time}s`
    }
  }, 1000)
  getCode({tel:loginForm.userName}).then(({data})=>{
    console.log(data,'验证码发送成功')
    if(data.code === 10000){
      ElMessage.success('验证码发送成功')
    }
  }

  )
}

const routerList = computed(() => store.state.menu.routerList)

/* ---------- 提交 ---------- */
const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败', fields)
      return
    }

    if (formType.value === 1) {
      // 注册
      userAuthentication(loginForm).then(({ data }) => {
        if (data.code === 10000) {
          ElMessage.success('注册成功')
          formType.value = 0 // 切换回登录
        }
      })
    } else {
      // 登录
      login(loginForm).then(({ data }) => {
        if (data.code === 10000) {
          ElMessage.success('登录成功')
          localStorage.setItem('pz_token', data.data.token)
          localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
          menuPermissions().then(({ data }) => {

               store.commit('dynamicMenu',data.data)
               console.log(routerList,'routerList');
               toRaw(routerList.value).forEach(item =>{
                router.addRoute('main',item)
               })
               router.push('/')
               
          })
        }
        
      })
    }
  })
}

/* ---------- 顶部图片 ---------- */
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href


</script>

<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
</style>